﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using NLog.Extensions.Logging;
using Microsoft.EntityFrameworkCore;

namespace 查看EFCore生成的SQL语句
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            //查看EF Core生成的SQL的方法

            //方法一：标准日志
            //在MyContext中注入ILoggerFactory，然后在其方法OnConfiguring中加入一行代码：
            //optionsBuilder.UseLoggerFactory(_loggerFactory);
            IServiceCollection services = new ServiceCollection();

            services.AddLogging(e => e.AddNLog());
            services.AddScoped<MyContext>();

            using (var sp = services.BuildServiceProvider())
            {
                using (var db = sp.GetRequiredService<MyContext>())
                {
                    Book book = new Book() { Title = "WPF", Price = 59, PubTime = new DateTime(2010, 1, 29) };
                    db.Books.Add(book);
                    await db.SaveChangesAsync();

                    //方法三：ToQueryString：只能获取查询操作的SQL
                    var query = db.Books.Where(e => e.Price > 10);
                    string sql = query.ToQueryString();     //using Microsoft.EntityFrameworkCore;
                    Console.WriteLine($"\n\n\n{sql}");
                }
            }


            //方法二：简单日志 ：optionsBuilder.LogTo(Console.WriteLine);
            //或者写成Lambda方式：在MyContext的OnConfiguring方法中加入一行代码：

            //optionsBuilder.LogTo(msg =>
            //{
            //    if (!msg.Contains("CommandExecuting")) return;
            //    Console.WriteLine(msg);
            //});          

        }
    }
}
